package com.lefevre.cms.web.action.help;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lefevre.cms.bean.*;
import com.lefevre.cms.bean.help.Help;
import com.lefevre.cms.bean.help.HelpType;
import com.lefevre.cms.service.help.HelpService;
import com.lefevre.cms.service.help.HelpTypeService;
import com.lefevre.cms.service.setting.SettingService;
import com.lefevre.cms.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 帮助管理
 *
 * @author Lefevre
 */
@Controller
public class HelpController {

    @Resource
    HelpService helpService;
    @Resource
    HelpTypeService helpTypeService;
    @Resource
    SettingService settingService;

    @ResponseBody
    @RequestMapping("/control/help/list")
    public String list(PageForm pageForm, Boolean visible) throws Exception {
        LambdaQueryWrapper<Help> wrapper = new LambdaQueryWrapper<>();

        if (visible != null && !visible) {
            wrapper.eq(Help::isVisible, false);
        } else {
            wrapper.eq(Help::isVisible, true);
        }

        PageView<Help> pageView = new PageView<Help>(settingService.findSystemSetting_cache().getBackstagePageNumber(), pageForm.getPage(), 10);
        int firstindex = (pageForm.getPage() - 1) * pageView.getMaxresult();

        wrapper.orderByDesc(Help::getId);
        Page<Help> helpPage = helpService.page(new Page<>(firstindex, pageView.getMaxresult()), wrapper);

        QueryResult<Help> qr = new QueryResult<>();

        qr.setTotalrecord(helpPage.getTotal());
        qr.setResultlist(helpPage.getRecords());

        pageView.setQueryResult(qr);

        List<Long> helpTypeIdList = new ArrayList<>();

        if (qr.getResultlist() != null && qr.getResultlist().size() > 0) {
            for (Help help : pageView.getRecords()) {
                helpTypeIdList.add(help.getHelpTypeId());
            }
            //查询分类名称
            List<HelpType> helpTypeList = helpTypeService.findByIdList(helpTypeIdList);
            if (helpTypeList != null && helpTypeList.size() > 0) {
                for (Help help : pageView.getRecords()) {
                    for (HelpType helpType : helpTypeList) {
                        if (help.getHelpTypeId().equals(helpType.getId())) {
                            help.setHelpTypeName(helpType.getName());
                            break;
                        }
                    }
                }
            }
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, pageView));
    }
}
